package com.leyou.search.listener;

import com.leyou.common.constants.MQConstants;
import com.leyou.item.dto.SpuDTO;
import com.leyou.itme.client.ItemClient;
import com.leyou.search.pojo.Goods;
import com.leyou.search.repository.GoodsRepository;
import com.leyou.search.service.SearchService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Component;

@Component
public class ItemListener {

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private SearchService searchService;

    /*监听器：监听哪个交换机，消息发送到哪个队列，绑定的routingKey*/



    /*商品上架，将商品添加到索引库*/
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.Queue.SEARCH_ITEM_UP,durable ="true"),
            exchange = @Exchange(name = MQConstants.Exchange.ITEM_EXCHANGE_NAME,type = ExchangeTypes.TOPIC),
            key = {MQConstants.RoutingKey.ITEM_UP_KEY}
    ))
    public void listenInsert(Long spuId){

        /*根据spuId获取Goods商品对象，保存索引*/

        SpuDTO spuDTO = itemClient.findSpuById(spuId);

        Goods goods = searchService.createGoods(spuDTO);

        goodsRepository.save(goods);
    }


    /*商品下架，将商品从索引库中删除商品*/
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.Queue.SEARCH_ITEM_DOWN,durable = "true"),
            exchange = @Exchange(name = MQConstants.Exchange.ITEM_EXCHANGE_NAME,type = ExchangeTypes.TOPIC),
            key = {MQConstants.RoutingKey.ITEM_DOWN_KEY}
    ))
    public void listenerDelete(Long spuId){
        SpuDTO spuDTO = itemClient.findSpuById(spuId);

        Goods goods = searchService.createGoods(spuDTO);

        goodsRepository.delete(goods);
    }
}
